﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Diagnostics.Eventing.Reader;
using System.Linq;
using System.Net;
using System.Net.Http.Headers;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using Dapper;
using DotnetSpider.DataFlow;
using DotnetSpider.DataFlow.Parser;
using DotnetSpider.DataFlow.Storage;
using DotnetSpider.Http;
using DotnetSpider.RequestSupplier;
using DotnetSpider.Scheduler.Component;
using DotnetSpider.Selector;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MongoDB.Bson;

using MySql.Data.MySqlClient;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RabbitMQ.Client;
using Serilog;
using static DotnetSpider.Lawyee.Src.LawSpider;
using StringContent = DotnetSpider.Http.StringContent;

namespace DotnetSpider.Lawyee.Src
{
	public class s17DataParser : DataParser
	{
		/// <summary>
		/// 生成细分过滤请求
		/// </summary>
		/// <param name="context"></param> 
		/// <param name="dataItemResult">左边菜单json</param>
		/// <param name="pageId"></param>
		/// <param name="condition"></param>
		public static void s17DataParserCreateSubRquest(DataContext context, JObject data, string pageId, JArray condition)
		{
			try
			{
				context.Request.SetProperty("lastConditionText", JsonConvert.SerializeObject(condition));

				foreach (var item in FamilyList)
				{
					JArray condition_ = (JArray)condition.DeepClone();

					JObject jobj = new JObject();

					jobj.Add(new JProperty("key", "s17"));

					jobj.Add(new JProperty("value", item));

					condition_.Add(jobj);

					if (condition_.Count() != 3)
					{
						string aaa = condition_.ToString();
					}

					Request request = ConditionRequst(context, condition_);

					context.AddFollowRequests(request);

				}
			}
			catch (Exception ex)
			{
				Log.Logger.Error(ex.Message + "!!!" + ex.StackTrace + "s17DataParser:CreateSubRquest:");
				throw ex;
			}
		}

		/// <summary>
		/// 进一步过虑生成请求
		/// </summary>
		/// <param name="context"></param>
		/// <param name="condition"></param>
		/// <returns></returns>
		protected static Request ConditionRequst(DataContext context, JArray condition)
		{
			Request request = null;

			try
			{
				string conditionText = JsonConvert.SerializeObject(condition);

				string pageId = context.Request.GetProperty("pageId");

				request = CreateDocDataItemRequest(conditionText, "s17DataParser", pageId);

				foreach (KeyValuePair<string, string> property in context.Request.Properties)
				{
					request.SetProperty(property.Key, property.Value);
				}

				request.SetProperty("conditionText", conditionText);


			}
			catch (Exception ex)
			{
				Log.Logger.Error(ex.Message + "!!!"+ ex.StackTrace + "s17DataParser:ConditionRequst:");
				throw ex;
			}

			return request;
		}



		public s17DataParser()
		{
			AddRequiredValidatorEx("s17DataParser");
		}

		protected override Task Parse(DataContext context)
		{
			try
			{
				//左边菜单json
				var result = CommonHelper.CommonParser(context);

				if (string.IsNullOrEmpty(result) || !result.StartsWith("{") || !result.EndsWith("}") )
				{
					Console.WriteLine("DocInfoSearch：!{}" + result);
					CommonHelper.RetryRequest(context);
					return Task.CompletedTask;
				}
				else
				{
					JObject dataItemResult = JObject.Parse(result);
					FilterData(context, dataItemResult);
				}

			}
			catch (Exception ex)
			{
				CommonHelper.RetryRequest(context);
				Log.Logger.Error(ex.Message + "!!!"+ ex.StackTrace + "s17DataParser:Parse:");
				//throw ex;
			}

			return Task.CompletedTask;

		}

		protected static void FilterData(DataContext context, JObject dataItemResult)
		{
			try
			{
				//总数
				int count = 0;
				if (dataItemResult.Property("s42") != null && dataItemResult["s42"].GetType() == typeof(JArray))
				{
					JArray jobjTotal = (JArray)dataItemResult["s42"];

					if (jobjTotal.Count > 0)
					{
						foreach (JObject everyYearTotal in jobjTotal)
						{
							count += int.Parse(everyYearTotal["count"].ToString());
						}
					}
				}
				else
				{
					//Console.WriteLine("返回为空：" + dataItemResult.ToJson());
					//throw new Exception("返回为空");
				}

				string pageId = context.Request.GetProperty("pageId");

				JArray condition = JArray.Parse(context.Request.GetProperty("conditionText"));

				Dictionary<string, string> properties = context.Request.Properties;

				if (count > 0)
				{
					ScrollPage(count, pageId, condition, context);

				}

				if (count > MaxRecord)  //小于当前设定值 
				{
					using (var conn = new SqlConnection(ConfigurationManager.AppSettings["StorageConnectionStringForDate"]))
					{
						conn.Execute(
						$"INSERT INTO recordnoall( [conditionText],[count],[createtimes]) VALUES ('" + CommonHelper.NoHtml(context.Request.GetProperty("conditionText")) + "'," + count + ",'" + DateTime.Now.ToString() + "') ");
					}
				}
			}
			catch (Exception ex)
			{
				Log.Logger.Error(ex.Message + "!!!"+ ex.StackTrace + "s17DataParser:FilterData:");
				using (var conn = new SqlConnection(ConfigurationManager.AppSettings["StorageConnectionStringForDate"]))
				{
					conn.Execute(
						$"INSERT INTO recordnoall ( [conditionText],[createtimes]) VALUES ('" + CommonHelper.NoHtml(ex.Message + ex.StackTrace) + ",  :s17DataParser,FilterData' ,'" + DateTime.Now.ToString() + "') ");
				}
				throw ex;

			}

		}












	}























}
